<template>
  <div class="container">
    <div class="form">
      <el-form ref="form" :model="form" :rules="rules" @keyup.enter.native="login">
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="用户名"
            class="form-item"
            prefix-icon="el-icon-user"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="密码"
            class="form-item"
            prefix-icon="el-icon-lock"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-button type="primary" class="btn" :loading="loginBtnLoading" @click="login">登录</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'Login',
  components: {},
  data() {
    return {
      form: {},
      rules: {
        username: [
          {
            required: true,
            message: '用户名不能为空',
            trigger: 'change'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'change'
          }
        ]
      },
      loginBtnLoading: false
    }
  },
  methods: {
    ...mapActions(['Login']),
    login: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loginBtnLoading = true
          this.Login(this.form)
            .then(res => {
              this.$message.success('登录成功')
              this.$router.push('/home')
              this.loginBtnLoading = false
            })
            .catch(() => {
              this.loginBtnLoading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .container {
    height: 100%;
    background-color: #d9ecff;

    .form {
      width: 300px;
      height: 300px;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);

      .form-item {
        width: 300px;
      }
      .btn {
        width: 300px;
      }
    }
  }
</style>
